/*
* @author haojieli
* CreateDate 2020-12-08
* Copyright (c) 2020 haojieli
*/
package com.hjieli.controller.admin.sys;

import java.util.List;

import java.util.Map;
import java.util.Random;
import java.text.NumberFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;


import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.bind.annotation.RestController;

import com.hjieli.config.security.util.MD5PasswordEncoder;
import com.hjieli.entity.SysUserInfo;
import com.hjieli.service.SysUserInfoService; 
import org.springframework.web.bind.annotation.RestController;


/**
*
* @author haojieli
* @since 2020-12-08
*/
@RestController
@RequestMapping("admin/sys/sysUserInfo")
public class SysUserInfoController {

    @Autowired
    private SysUserInfoService sysUserInfoService;

    /**
     *   sys_user_info表的添加页面
    **/
	@RequestMapping("add")
	public ModelAndView add(String id, HttpServletRequest request) {
		ModelAndView modelAndView = new ModelAndView("admin/sys/sysUserInfo/view");
		if(id == null) {
			modelAndView.addObject("sysUserInfo", new SysUserInfo());
		}else {
			QueryWrapper<SysUserInfo> wrapper = new QueryWrapper<>();
			wrapper.eq("id", id);
			SysUserInfo sysUserInfo = sysUserInfoService.getOne(wrapper);
			modelAndView.addObject("sysUserInfo", sysUserInfo);
		}
		return modelAndView;
	}
    /**
     *   保存sys_user_info表的数据
    **/
    @RequestMapping(value = "save")
	public String save(@RequestBody Map<String,String> queryParams, HttpServletRequest request) {
        SysUserInfo sysUserInfo = new SysUserInfo();
//        if(queryParams.containsKey("id") && !queryParams.get("id").toString().equals("")){
//            sysUserInfo.setId(queryParams.get("id").toString());
//        }
        if(queryParams.containsKey("userName") && !queryParams.get("userName").toString().equals("")){
            sysUserInfo.setUserName(queryParams.get("userName").toString());
        }
        String account = accountGen();
        sysUserInfo.setAccount(account);
        sysUserInfo.setPassword(new MD5PasswordEncoder().encode(account));//设置默认密码
        sysUserInfo.setIsEnable(1);
		sysUserInfo.setCreateTime(LocalDateTime.now());
		sysUserInfoService.save(sysUserInfo);
		return "success";
	}
    /**
     *   更新sys_user_info表的数据
    **/
    @RequestMapping(value = "update")
	public String update(@RequestBody SysUserInfo sysUserInfo, HttpServletRequest request) {
		sysUserInfo.setUpdateTime(LocalDateTime.now());
		sysUserInfoService.updateById(sysUserInfo);
		return "success";
	}


    /**
     *   删除sys_user_info表的数据
    **/
    @RequestMapping("delete")
	public String delete(@RequestBody Map<String,String> params, HttpServletRequest request) {
		
		String ids = params.get("ids").toString();
		//查询文章信息
		QueryWrapper<SysUserInfo> wrapper = new QueryWrapper<>();
		wrapper.in("id", ids.split(","));
		
	    SysUserInfo sysUserInfo = new SysUserInfo();
		sysUserInfo.setIsEnable(0);
		sysUserInfo.setCreateTime(LocalDateTime.now());
		sysUserInfoService.update(sysUserInfo,wrapper);

		return "success";
	}
    
    
    /**
     *   到sys_user_info表的列表页面
    **/
	@RequestMapping("list")
	public ModelAndView list(HttpServletRequest request) {
		ModelAndView modelAndView = new ModelAndView("admin/sys/sysUserInfo/list");
		return modelAndView;
	}

    /**
     *  查询sys_user_info表的数据列表
    **/
    @RequestMapping("list/data")
	public String listdata(Integer page, Integer rows,
                            String id,
                            String userName,
                            String password,
                            String account,
                            LocalDateTime createTime,
                            LocalDateTime updateTime,
                            Integer isEnable,
                            HttpServletRequest request) {
		
		if(page == null || page < 0) {
			page = 1;
		}
		if(rows == null || rows < 10) {
			rows = 10;
		} else if(rows > 50) {
			rows = 50;
		}
		Page<SysUserInfo> pageObj = new Page(page,rows);          //1表示当前页，而10表示每页的显示显示的条目数

        QueryWrapper<SysUserInfo> queryWrapper = new QueryWrapper();
		queryWrapper.eq(true,"is_enable", 1);
        
            if(id != null && !id.equals("")) {
                queryWrapper.eq(true,"id", id);
            }
            if(userName != null && !userName.equals("")) {
                queryWrapper.eq(true,"user_name", userName);
            }
            if(password != null && !password.equals("")) {
                queryWrapper.eq(true,"password", password);
            }
            if(account != null && !account.equals("")) {
                queryWrapper.eq(true,"account", account);
            }
            if(createTime != null && !createTime.equals("")) {
                queryWrapper.eq(true,"create_time", createTime);
            }
            if(updateTime != null && !updateTime.equals("")) {
                queryWrapper.eq(true,"update_time", updateTime);
            }
            if(isEnable != null && !isEnable.equals("")) {
                queryWrapper.eq(true,"is_enable", isEnable);
            }
		queryWrapper.orderByDesc("create_time");

		
		Page<SysUserInfo> result = sysUserInfoService.listByCondition(pageObj, queryWrapper);
		Gson gson = new Gson();
		String dataStr = gson.toJson(result);
		JsonElement jsonElement = JsonParser.parseString(dataStr);
		
		JsonObject jsonObject = jsonElement.getAsJsonObject();
		jsonObject.remove("isAsc");
		jsonObject.remove("limit");
		jsonObject.remove("offset");
		jsonObject.remove("openSort");
		jsonObject.remove("optimizeCountSql");
		jsonObject.remove("searchCount");
		jsonObject.add("rows", jsonObject.get("records").getAsJsonArray());
		jsonObject.remove("records");
		return jsonObject.toString();
	}
    
    //判定系统账号
    public String accountGen() {
    	String account = "";
		//生成
		int sumCount = sysUserInfoService.count();
		int randomNum = new Random().nextInt(9) + 1;
		account = "" + randomNum + sumCount;
		NumberFormat formatter = NumberFormat.getNumberInstance();   
        formatter.setMinimumIntegerDigits(6);   
        formatter.setGroupingUsed(false);
        account = "C" + (new Random().nextInt(9) + 1) +formatter.format(Integer.parseInt(account));
      
    	//先判断是否存在，在生成
    	if(accountIsExsit(account)) {
    		return accountGen();
    	}
    	return account;
    }
    
    public boolean accountIsExsit(String account) {

    	QueryWrapper<SysUserInfo> queryWrapper = new QueryWrapper<SysUserInfo>();
    	queryWrapper.eq("account", account);
    	int num = sysUserInfoService.count(queryWrapper);
    	if(num == 0) {
    		return false;
    	}
    	return true;
    }

}

